package info.magnolia.blossom.sample.cv.util;

import info.magnolia.cms.beans.runtime.Document;
import info.magnolia.cms.beans.runtime.MultipartForm;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * User: peterbalazs
 * Date: 3/8/13
 * Time: 3:15 PM
 * To change this template use File | Settings | File Templates.
 */
public class WebUtil {

    public static final String ERROR_MSG = "errorMsg";
    public static final String ERROR_PAGE_PATH = "components/error.jsp";

    public static final String PARAM_UPLOAD_PICTURE_PARAM = "picture";

    /**
     * Class logger.
     */
    private static final Logger logger = Logger.getLogger(WebUtil.class);

    public static byte[] getFileContent(final HttpServletRequest request, final String fileParamName) {
        final MultipartForm form = (MultipartForm) request.getAttribute(MultipartForm.REQUEST_ATTRIBUTE_NAME);
        if (form != null) {
            final Document document = form.getDocument(fileParamName);
            try {
                return IOUtils.toByteArray(document.getStream());
            } catch (IOException ioe) {
                logger.error("Error reading uploaded file", ioe);
            }
        }
        return null;
    }

    public static String getFileName(final HttpServletRequest request, final String fileParamName) {
        final MultipartForm form = (MultipartForm) request.getAttribute(MultipartForm.REQUEST_ATTRIBUTE_NAME);
        if (form != null) {
            final Document document = form.getDocument(fileParamName);
            return document.getFileNameWithExtension();
        }
        return null;
    }
}
